package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.config.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备管理Service业务层处理
 *
 * @author alexis
 * @date 2025-01-10
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliyun;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public void updateDevice(Device device) {
        try {
            deviceMapper.updateById(device);
        } catch (Exception e) {
            throw new BaseException("修改失败");
        }
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        request.setIotInstanceId(aliyun.getIotInstanceId());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> nicknameInfos = new ArrayList<>();
        nicknameInfos.add(new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo()
                .setNickname(device.getNickname())
                .setProductKey(device.getProductKey())
                .setDeviceName(device.getDeviceName()));
        request.setDeviceNicknameInfo(nicknameInfos);
        BatchUpdateDeviceNicknameResponse response;

        try {
            response = client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new BaseException("修改失败");
        }
        if (!response.getBody().getSuccess()) {
            throw new BaseException("修改失败");
        }

    }

    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProductList() {
        QueryProductListRequest request = new QueryProductListRequest().setCurrentPage(1).setPageSize(10).setIotInstanceId(aliyun.getIotInstanceId());
        QueryProductListResponse queryProductListResponse;
        try {
            queryProductListResponse = client.queryProductList(request);
            if (!queryProductListResponse.getBody().getSuccess()) {
                new BaseException("获取设备列表失败");
            }
            List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productInfo = queryProductListResponse.getBody().getData().getList().getProductInfo();
            String jsonStr = JSONUtil.toJsonPrettyStr(productInfo);
            redisTemplate.opsForValue().set(Constants.IOT_PRODUCT_LIST_ALL, jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<ProductVo> allProduct() {
        String jsonStr = redisTemplate.opsForValue().get(Constants.IOT_PRODUCT_LIST_ALL);
        List<ProductVo> list = JSONUtil.toList(jsonStr, ProductVo.class);
        return list;
    }

    @Override
    public void registerDevice(DeviceDto deviceDto) {
        String deviceName = deviceDto.getDeviceName();
        QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
        deviceQueryWrapper.eq("device_name", deviceName);
        Long l = deviceMapper.selectCount(deviceQueryWrapper);
        if (l > 0) {
            throw new BaseException("设备名称重复");
        }
        RegisterDeviceRequest request = deviceDto.getRegisterDeviceRequest();
        RegisterDeviceRequest registerDeviceRequest = request.setIotInstanceId(aliyun.getIotInstanceId());
        RegisterDeviceResponse registerDeviceResponse;
        try {
            registerDeviceResponse = client.registerDevice(registerDeviceRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!registerDeviceResponse.getBody().getSuccess()) {
            throw new BaseException("阿里云平台设备注册失败");
        }
        String iotId = registerDeviceResponse.getBody().getData().getIotId();
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }
        Device bean = BeanUtil.toBean(deviceDto, Device.class);
        bean.setIotId(iotId);

        try {
            int i = deviceMapper.insertDevice(bean);
        } catch (Exception e) {
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest().setIotInstanceId(aliyun.getIotInstanceId()).setProductKey(bean.getProductKey()).setDeviceName(bean.getDeviceName()).setIotId(bean.getIotId());
            try {
                client.deleteDevice(deleteDeviceRequest);
            } catch (Exception ex) {
                throw new BaseException("删除失败");
            }
            throw new BaseException("设备名重复或者位置重复,插入失败");
        }

    }

    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest().setIotInstanceId(aliyun.getIotInstanceId()).setIotId(deviceDto.getIotId()).setProductKey(deviceDto.getProductKey());
        QueryDeviceDetailResponse queryDeviceDetailResponse;

        try {
            queryDeviceDetailResponse = client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        DeviceVo deviceVo = BeanUtil.copyProperties(queryDeviceDetailResponse.getBody().getData(), DeviceVo.class);
        Device device = deviceMapper.selectOne(Wrappers.lambdaQuery(Device.class).eq(Device::getIotId, deviceDto.getIotId()));
        BeanUtil.copyProperties(device, deviceVo, CopyOptions.create().ignoreNullValue());
        return deviceVo;
    }

    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliyun.getIotInstanceId());
        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!response.getBody().getSuccess()) {
            throw new BaseException("查询iot平台失败");
        }

        return AjaxResult.success(response.getBody().getData());
    }

    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliyun.getIotInstanceId());
        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!response.getBody().getSuccess()) {
            throw new BaseException("查询iot平台失败");
        }

        return AjaxResult.success(response.getBody().getData());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDevice(DeviceDto deviceDto) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setIotInstanceId(aliyun.getIotInstanceId());
        request.setProductKey(deviceDto.getProductKey());
        Device device = deviceMapper.selectOne(Wrappers.lambdaQuery(Device.class).eq(Device::getIotId, deviceDto.getIotId()));
        if (device == null) {
            throw new BaseException("设备不存在");
        }
        request.setDeviceName(device.getDeviceName());
        request.setIotId(deviceDto.getIotId());
        DeleteDeviceResponse deleteDeviceResponse;
        try {
            deleteDeviceResponse = client.deleteDevice(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!deleteDeviceResponse.getBody().getSuccess()) {
            throw new BaseException("删除设备失败");
        }
        deviceMapper.deleteDeviceById(device.getId());
    }


}
